from blog.models import Author, Blog, Setting, Category, Entry, Engine
from django import newforms as forms
from google.appengine.ext.db import djangoforms

# Create your models here.
class EngineForm(djangoforms.ModelForm):
  class Meta:
    model = Engine
    exclude = ['multiblog']

class BlogForm(djangoforms.ModelForm):
  class Meta:
    model = Blog
    exclude = ['engine']

class SettingForm(djangoforms.ModelForm):
  class Meta:
    model = Setting

class CategoryForm(djangoforms.ModelForm):
  class Meta:
    model = Category
    exclude = ['blog']

class EntryForm(djangoforms.ModelForm):
  class Meta:
    model = Entry
    exclude = ['author', 'blog']

class EntryCategoryForm(forms.Form):
  selected = forms.BooleanField(required=False)
  
  def __init__(self, category, entry=None, *args, **kwargs):
    defaults = {'prefix': 'category_%s' % category.id}
    defaults.update(kwargs)
    super(EntryCategoryForm, self).__init__(*args, **defaults)
    self.category, self.entry = category, entry
    self.fields['selected'].label = self.name
    self.fields['selected'].initial = entry and entry.is_in_category(category)
    
  def save(self):
    if self.cleaned_data['selected']:
      self.entry.add_category(self.category)
    elif self.entry.is_in_category(self.category):
      self.entry.remove_category(self.category)
    
  @property
  def name(self): return self.category.name
  
  @staticmethod
  def collectionFor(categories, entry=None, data=None):
    return [EntryCategoryForm(c, entry=entry, data=data) for c in categories]
    
class SetupForm(forms.Form):
  title = forms.CharField(required=True)
  subtitle = forms.CharField(required=True)
  domain = forms.CharField(required=True)
  
  def __init__(self, engine=None, blog=None, domain=None, *args, **kwargs):
    super(SetupForm, self).__init__(*args, **kwargs)
    self.engine = engine
    self.blog = blog
    
    self.fields['domain'].initial = self.engine and engine.domain or domain
    if self.blog:
      self.fields['title'].initial = blog.title
      self.fields['subtitle'].initial = blog.subtitle
  
  def __str__(self):
    return super(SetupForm,self).__str__()
  
  def save(self):
    domain = self.cleaned_data['domain']
    self.engine = self.engine or Engine(multiblog=False, domain=domain)
    self.engine.put()
    
    self.blog = self.blog or Blog(engine=self.engine, name="default")
    self.blog.put()
    
    title_setting = self.blog.get_setting("title") or Setting(name="title", blog=self.blog)
    title_setting.value = self.cleaned_data['title']
    title_setting.put()
    
    subtitle_setting = self.blog.get_setting("subtitle") or Setting(name="subtitle", blog=self.blog)
    subtitle_setting.value = self.cleaned_data['subtitle']
    subtitle_setting.put()